package com.ymt.bpm.util.w3cdom;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.logging.Logger;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ymt.bpm.engine.bpmn.BpmnNamespaceContext;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;


/**
 * XML处理工具类.
 * @author Johnny
 *
 */
public class XmlUtil {
	
	static Logger logger = Logger.getLogger(XmlUtil.class.getName());
	
	/**
	 * 根据Xpath获取xml元素属性列表，返回json数组.
	 * @param sourceXmlStr
	 * @param expression
	 * @param attrlist
	 * @return
	 * @throws XPathExpressionException
	 * @throws IOException
	 */
	public static JSONArray getElementAttrs(String sourceXmlStr, String expression, @SuppressWarnings("rawtypes") List attrlist) throws XPathExpressionException, IOException {
		JSONArray arr = new JSONArray();
		NodeList nl = getNodesByXPath(sourceXmlStr, expression);
		if (nl != null && nl.getLength()>0) {
			for (int i=0; i<nl.getLength(); i++) {
				JSONObject attrs = new JSONObject();
				for (int j=0; j<attrlist.size(); j++) {
					String attrName = (String) attrlist.get(j);
					String attrValue = null;
					Node attrNode = nl.item(i).getAttributes().getNamedItem((String) attrlist.get(j));
					if (attrNode != null) {
						attrValue = attrNode.getNodeValue();
					}
					attrs.put(attrName, attrValue);
				}
				arr.add(attrs);
			}
		}
		return arr;
	}
	
	/**
	 * 根据Xpath获取xml元素或属性列表.
	 * @param sourceXmlStr
	 * @param expression
	 * @return
	 * @throws XPathExpressionException
	 * @throws IOException
	 */
	private static NodeList getNodesByXPath(String sourceXmlStr, String expression) throws XPathExpressionException, IOException {
		XPathFactory f = XPathFactory.newInstance();
		XPath xpath = f.newXPath();
		xpath.setNamespaceContext(new BpmnNamespaceContext());
        XPathExpression ex = xpath.compile(expression);
        NodeList nl = (NodeList) ex.evaluate(new InputSource(new StringReader(sourceXmlStr)), XPathConstants.NODESET);
        
        /*logger.finer(nl.getLength());
        for (int i=0; i<nl.getLength(); i++) {
        	logger.finer("==========================================");
        	logger.finer("="+nl.item(i).getLocalName());
            logger.finer("="+nl.item(i).getBaseURI());
            logger.finer("="+nl.item(i).getNamespaceURI());
            logger.finer("="+nl.item(i).getNodeName());
            logger.finer("="+nl.item(i).getNodeType());
            logger.finer("="+nl.item(i).getNodeValue());
            logger.finer("="+nl.item(i).getPrefix());
            logger.finer("="+nl.item(i).getTextContent());
            Node node = nl.item(i);
        }*/
        
        return nl;
	}

}
